﻿/*----------------------------------------------------------------
       // Copyright (C) 2008 安华顺通(北京)科技有限公司
       // 版权所有。 
       //
       // 文件名：SysTreeView.cs
       // 文件功能描述：TreeView,TreeNode的继承扩展，TreeViewOpr提供对TreeView的操作。
       //
       // 
       // 创建标识：杨波
       //
       // 修改标识：杨波20080905
       // 修改描述：添加SysTreeView响应F2，可编辑树结点。
       //
       // 修改标识：杨波20081027
       // 修改描述：修改树结点的填充模式，将以前的在显示子结点便填充其所有孙子结点改为如果有孙子结点先填充一个假结点，在展开前再填充所有的孙子结点。
 * 
 * 
 *     // 修改标识：
       // 修改描述：
//----------------------------------------------------------------*/

#region UsingStatements

using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Resources;
using System.Reflection;

#endregion

namespace RuleCode.ObjectTree
{
    [ToolboxBitmap(typeof(SysTreeView), "TreeView.bmp")]
    public class SysTreeView : TreeView
    {
        private string baseNodePath;
        //private MySharp.MySharpIDE ide;

        public string BaseNodePath
        {
            set { baseNodePath = value; }
            get { return baseNodePath; }
        }

        public SysTreeView()
        {
            Init();
        }

        private void Init()
        {
            //this.ContextMenuStrip = new BaseContextMenu();
            HideSelection = true;
            PathSeparator = "/";
            /*this.MultiSelect = MWCommon.TreeViewMultiSelect.MultiSameBranchAndLevel;
            this.AllowNoSelNode = false;
            //this.CanSelect = true;
            this.ScrollToSelNode = true;*/

            LabelEdit = true;
            AllowDrop = true;

            ItemDrag += SysTreeView_ItemDrag;
            DragEnter += SysTreeView_DragEnter;
            DragDrop += SysTreeView_DragDrop;
            DragOver += SysTreeView_DragOver;
        }

        private void SysTreeView_DragOver(object sender, DragEventArgs e)
        {               
            //SysTreeNode HighlightedNode=null;
            //throw new System.NotImplementedException();
            Point targetPoint = PointToClient(new Point(e.X, e.Y));
            SysTreeNode targetNode = (SysTreeNode)(GetNodeAt(targetPoint));
            SysTreeNode draggedNode = (SysTreeNode)(e.Data.GetData(typeof(SysTreeNode)));

            if (NodesTransaction.Instance.isCanBeDropped(draggedNode, targetNode))
            {
                SelectedNode = targetNode;

                Util.SelectedNode = (SysTreeNode)SelectedNode;
                e.Effect = e.AllowedEffect;


                //HighlightNode(targetNode, true);
                //HighlightedNode = targetNode;
            }
            else
            {
                //e.Effect = DragDropEffects.None;
                e.Effect = DragDropEffects.None;
                SelectedNode = null;
                /*if (HighlightedNode != targetNode)
                {
                    LowlightNode(HighlightedNode);
                }*/
                //this.SelectedNode = null;
            }
            //this.SelectedNode = this.GetNodeAt(targetPoint);
        }

        //高亮显示一个Node
        public void HighlightNode(TreeNode tn, bool bTreeViewActive)
        {
            if (bTreeViewActive)
            {
                if (tn.BackColor != SystemColors.Highlight)
                {
                    tn.BackColor = SystemColors.Highlight;
                }

                if (tn.ForeColor != SystemColors.HighlightText)
                {
                    tn.ForeColor = SystemColors.HighlightText;
                }
            }
            else
            {
                if (tn.BackColor != SystemColors.Control)
                {
                    tn.BackColor = SystemColors.Control;
                }

                if (tn.ForeColor != ForeColor)
                {
                    tn.ForeColor = ForeColor;
                }
            }
        }

        //取消高亮显示Node
        public void LowlightNode(TreeNode tn)
        {
            if (tn.BackColor != BackColor)
            {
                tn.BackColor = BackColor;
            }

            if (tn.ForeColor != ForeColor)
            {
                tn.ForeColor = ForeColor;
            }
        }

        //是否可以接受拖放结点


        private void SysTreeView_DragDrop(object sender, DragEventArgs e)
        {
            //throw new System.NotImplementedException();
            //if ()
            Point targetPoint = PointToClient(new Point(e.X, e.Y));
            SysTreeNode targetNode = (SysTreeNode)(GetNodeAt(targetPoint));
            SysTreeNode draggedNode = (SysTreeNode)(e.Data.GetData(typeof(SysTreeNode)));

            if (!draggedNode.Equals(targetNode) && !ContainsNode(draggedNode, targetNode))
            {
                //SysTreeNode copy = (SysTreeNode)draggedNode.Clone();
                //targetNode.Nodes.Add(copy);
                //this.SelectedNode = copy;
                //LowlightNode(targetNode);
                //HighlightNode(copy,true);
                //targetNode.Nodes.Add((SysTreeNode)draggedNode.Clone());
                Util.ActiveTreeView = this;
                NodesTransaction.Instance.doDrop(draggedNode, targetNode);
            }
            targetNode.Expand();
        }

        private void SysTreeView_DragEnter(object sender, DragEventArgs e)
        {
            //throw new System.NotImplementedException();
            e.Effect = e.AllowedEffect;
        }

        private void SysTreeView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            //throw new System.NotImplementedException();
            if (e.Button == MouseButtons.Left)
            {
                //this.AllowDrop = true;
                SelectedNode = (SysTreeNode)e.Item;
                DoDragDrop(e.Item, DragDropEffects.Copy);
            }
            /* if (e.Button == MouseButtons.Right)
                 this.AllowDrop = true;
             DoDragDrop(e.Item, DragDropEffects.Scroll);
             */
        }

        private bool ContainsNode(SysTreeNode node1, SysTreeNode node2)
        {
            // Check the parent node of the second node.
            if (node2.Parent == null) return false;
            if (node2.Parent.Equals(node1)) return true;

            // If the parent node is not null or equal to the first node, 
            // call the ContainsNode method recursively using the parent of 
            // the second node.
            return ContainsNode(node1, (SysTreeNode)node2.Parent);
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            //this.BeginUpdate();
            base.OnMouseClick(e);
            SelectedNode = GetNodeAt(e.X, e.Y);
            //Util.SelectedNode = this.SelectedNode;
            Util.SelectedNode = (SysTreeNode)SelectedNode;

            Util.ActiveTreeView = this;

            if (e.Button == MouseButtons.Right)
            {
                //TableContextMenu menu = new TableContextMenu();

                Util.ParentTreeView = this;
                //this.SelectedNode.ContextMenuStrip = menu.getContextMenuStrip();
                SelectedNode.ContextMenuStrip =
                    SysContextMenu.getContextMenu(
                        ((SysTreeNode)SelectedNode).SysXmlNode.Attributes.GetNamedItem("Type").Value);
                if (GetNodeAt(e.X, e.Y) == null)
                    SelectedNode.ContextMenuStrip = null;
            }
            else
            {
                if (e.Button == MouseButtons.Left)
                {
                }
            }
            if (Util.SelectedNode.Property == null)
            {
                Util.SetPropertyContent(Util.SelectedNode);
            }
            else Util.SetPropertyContent(Util.SelectedNode.Property);

            //this.EndUpdate();
        }

        protected override void OnDoubleClick(EventArgs e)
        {
            //if (Util.SelectedNode.SysXmlNode.Attributes["Type"].Value == "TableMethod")
            //{
            //    if (Util.SelectedNode.Property == null)
            //    {
            //        Util.SetPropertyContent(Util.SelectedNode);
            //    }
            //    else Util.SetPropertyContent(Util.SelectedNode.Property);
            //    SysMethodEditor editor = new SysMethodEditor();
            //    if (Util.SelectedNode.Property != null)
            //        editor.Value = ((MethodProperty)Util.SelectedNode.Property).Content;
            //    editor.ShowDialog();
            //    editor.MdiParent = Util.MdiParent;
            //    if (Util.SelectedNode.Property != null)
            //    {
            //        ((MethodProperty)Util.SelectedNode.Property).Content = editor.Value;
            //    }
            //    //打开方法编辑器的优先级高于折叠或展开

            //}
            if (Util.SelectedNode.SysXmlNode.Attributes["Type"].Value.Equals(OT.Class))
            {
                //ide = Util.IDE ?? new MySharp.MySharpIDE();
                //Util.IDE = ide;
                //ide.OpenFile(Util.GetClassPath + "\\" + Util.SelectedNode.Property.ID + ".cs");
                //ide.MdiParent = Util.MdiParent;

                ////if (ide.Visible.Equals(false))
                ////{
                ////    ide.Visible = true;
                ////}
                ////else
                ////{
                //ide.Show();
                //}

                //Class1 c = new Class1(Util.MdiParent);

                ////main.MdiParent = Util.MdiParent;
            }
            //if (Util.SelectedNode.SysXmlNode.Attributes["Type"].Value.Equals(OT.Table))
            //{
            //    ide = ide ?? new MySharp.MySharpIDE();

            //    ide.OpenFile(Util.OTPath + @"\Module\Tables" + "\\" + Util.SelectedNode.Property.ID + ".cs");
            //    ide.MdiParent = Util.MdiParent;


            //    ide.Show();

            //}
            base.OnDoubleClick(e);
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            //this.BeginUpdate();
            base.OnMouseDown(e);
            Util.ActiveTreeView = this;
            //this.SelectedNode = this.GetNodeAt(e.X, e.Y);
            //this.SelectedNode = this.GetNodeAt(e.X, e.Y);


            Util.SelectedNode = (SysTreeNode)SelectedNode;
            //this.EndUpdate();
        }

        protected override void OnBeforeExpand(TreeViewCancelEventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            if ((e.Node != null) && (e.Node.Nodes.Count == 1) && (e.Node.Nodes[0].Text.Equals("JustForFun")))
            {
                e.Node.Nodes.Clear();
                ((SysTreeNode)e.Node).FillSubNodes((SysTreeNode)e.Node);
            }
            Cursor = Cursors.Default;
            base.OnBeforeExpand(e);
        }

        protected override void OnBeforeLabelEdit(NodeLabelEditEventArgs e)
        {
            if (IsDisallowLabelEditRegExSatisfied(e.Node.Text))
            {
                e.CancelEdit = true;
            }
            Util.SetPropertyContent(Util.SelectedNode);
            base.OnBeforeLabelEdit(e);
        }

        // ReSharper disable MemberCanBeMadeStatic
        private bool IsDisallowLabelEditRegExSatisfied(IEquatable<string> strLabelText)
        // ReSharper restore MemberCanBeMadeStatic
        {
            bool bRetVal = false;

            if (Util.DisallowLabelEditRegEx != string.Empty)
            {
                //bRetVal = Regex.IsMatch(strLabelText, Util.DisallowLabelEditRegEx, RegexOptions.Singleline);
                IEnumerator enu = Util.DisAllowLabelEditStrings.GetEnumerator();
                while (enu.MoveNext())
                {
                    string str = (string)enu.Current;
                    if (strLabelText.Equals(str))
                    {
                        bRetVal = true;
                        break;
                    }
                }
            }

            return bRetVal; //throw new System.NotImplementedException();
        }

        protected override void OnAfterLabelEdit(NodeLabelEditEventArgs e)
        {
            bool canBeDown = true;
            bool disableOtherMessage = false;
            TreeNode parent = e.Node.Parent;
            foreach (TreeNode node in parent.Nodes)
            {
                if (string.IsNullOrEmpty(e.Label) || ((e.Label == node.Text) && (e.Node != node)))
                {
                    canBeDown = false;
                }
            }
            //结点名不能以数字开始
            if (canBeDown)
            {
                //以英语字母和汉字开始，后边可包括数字
                //if (!Regex.IsMatch(e.Label, "^[A-Za-z\u4E00-\u9fa5]+[A-Za-z0-9\u4E00-\u9fa5]+$"))  //Origin Code
                if (!Regex.IsMatch(e.Label, "^[_A-Za-z0-9\u4E00-\u9fa5]+$"))  //Modified By DingYuliang
                {
                    canBeDown = false;
                    MessageBox.Show("类型名不符合标准。");
                    disableOtherMessage = true;
                }
            }
            if (canBeDown)
            {
                if ((((SysTreeNode)e.Node).Property) is NameProperty)
                {
                    ((NameProperty)((SysTreeNode)e.Node).Property).Name = e.Label;
                }
                //Util.changeXmlNodeName(((SysTreeNode)e.Node).SysXmlNode, e.Label);
                Util.SelectedNode.SysXmlNode = Util.changeXmlNodeName(Util.SelectedNode.SysXmlNode, e.Label);
                Util.PropertyGrid.Refresh();
                //Util.SelectedNode.Text = e.Label;
                //将名称修改同步到DB
                SynchronizeToDB.SynchronizeAfterLabelEdit(Util.SelectedNode, e.Label, Util.SelectedNode.Text);
                Util.SelectedNode.Name = e.Label;
                //设置该类型的List过期
                string type = Util.SelectedNode.SysXmlNode.Attributes.GetNamedItem("Type").Value;
                ObjectList.Instance.SetTypeExpire(type);
                //修改源码中的类型名
                SynchronizeToFile.SynchronizeAfterLabelEdit(Util.SelectedNode.Property.ID, type, e.Label, e.Node.Text);
                if (Util.PropertyGrid.SelectedGridItem.Parent.GridItems["Label"] != null)
                {
                    Util.PropertyGrid.SelectedGridItem.Parent.GridItems["Label"].Select();

                }

                Util.PropertyGrid.Focus();

            }
            else
            {
                e.CancelEdit = true;
                if (e.Label != null && disableOtherMessage == false) //表示没有任何更改
                    MessageBox.Show("结点名称不能为空或已存在相同名称结点");

            }
            base.OnAfterLabelEdit(e);
        }

        /// <summary>
        /// 在状态栏显示相关信息。
        /// </summary>
        /// <param name="e"></param>
        protected override void OnAfterSelect(TreeViewEventArgs e)
        {
            //Util.MdiParent.toolStripStatusLabel1.Text = baseNodePath + SelectedNode.FullPath + ":    " +
            //                                            SelectedNode.GetNodeCount(false) + " objects";
            if (Util.OTControl!=null)
            {
                Util.OTControl.PropertyWindowTabPage.Text = SelectedNode.Text;
            }
            base.OnAfterSelect(e);
        }

        /// <summary>
        /// 响应键盘击键事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F2:
                    {
                        if (SelectedNode != null)
                        {
                            SelectedNode.BeginEdit();
                        }

                        break;
                    }
            }
            if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.Up)
            {
                NodesTransaction.Instance.UpNode(Util.SelectedNode);
            }
            if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.Down)
            {
                NodesTransaction.Instance.DownNode(Util.SelectedNode);
            }
            base.OnKeyDown(e);
        }
    }

    public class TreeViewOpr
    {
        private static XmlDocument xdoc;
        public static XmlDocument nodesTemplate;
        public static XmlDocument typeMaxNum;
        private static TreeViewOpr treeViewOpr;
        private static string otXML;
        private static string nodesTemplateXML;
        private static string typeMaxNumXML;
        public static ArrayList LivelySysTreeViewList;
        //private static SysTreeView rootTreeview;


        public TreeViewOpr()
        {
            //base();
            //this.init();
            LivelySysTreeViewList = new ArrayList();
        }

        private void init(SysTreeView treeView)
        {
            //read aot.xml once in initial()
            /**string xmlpath;
            
            xmlpath = XMLPath();
            //MessageBox.Show(xmlpath);
              XmlTextReader xreader = new XmlTextReader(xmlpath);

            XmlDocument xdoc = new XmlDocument();

            xdoc.Load(xreader);
            xreader.Close();**/
            //XmlNode xnode = DocumentElement;

            XmlNode xnode = getXmlDocument().DocumentElement;
            nodesTemplate = getNodesTemplateXML();
           // typeMaxNum = getTypeMaxNumXML();
            // XmlNodeList xnodelist = xdoc.DocumentElement.ChildNodes;
            //treeView.ImageList = SysIcoList.getIcoList();
            /*if (rootTreeview == null)
            {
                this.fillNodes(xnode, treeView.Nodes);
                rootTreeview = treeView;
                
                
            }
            else //treeView.Nodes = this.rootTreeview.TopNode.Nodes;
            {
                //TreeNode tmpRoot = (TreeNode)rootTreeview.TopNode.Clone();
                //treeView.Nodes.Add(tmpRoot);
                treeView.Nodes.Add((TreeNode)rootTreeview.TopNode.Clone());

            }*/
            fillNodes(xnode, treeView.Nodes);

            //在OT中显示的所有图标，在其它地方也应只调用这一个ImageList，节约资源

            //填充AOT一个结点

            //再填充AOT的子结点，用填充结点的方法
        }
        public static void Reload()
        {
            SetSysXmlExpire();
        }
        public static SysTreeView getSysTreeView()
        {
            
            SysTreeView sysTreeView = new SysTreeView();
            sysTreeView.AllowDrop = true;
            //显示Tooltips
            sysTreeView.ShowNodeToolTips = true;


            sysTreeView.ImageList = SysIcoList.getIcoList();
            TreeViewOpr operation = getTreeViewOpr();


            operation.init(sysTreeView);
            ((SysTreeNode)(sysTreeView.Nodes[0])).ExpandNode();
            //sysTreeView.Nodes[0].Expand();
            sysTreeView.BaseNodePath = "";

            return sysTreeView;
        }

        public static SysTreeView getSubTreeView(SysTreeNode treeNode, SysTreeView treeView)
        {
            SysTreeView sysTreeView = new SysTreeView();
            sysTreeView.ImageList = SysIcoList.getIcoList();
            //如果结点没有展开时
            if (!treeNode.IsExpanded)
            {
                treeView.BeginUpdate();
                /**treeNode.Expand();//此处先展开后折叠是为了解决当从结点打开新窗口时，其子子结点尚未填充，导致新窗口的显示错误。
                treeNode.Collapse();
                treeNode.Expand();
                 **/
                treeNode.Toggle();
                treeNode.Toggle();
                treeView.EndUpdate();
            }
            SysTreeNode newnode = (SysTreeNode)(treeNode.Clone());
            sysTreeView.Nodes.Add(newnode);
            sysTreeView.Nodes[0].Expand();
            if (treeNode.Parent != null)
            {
                sysTreeView.BaseNodePath = treeView.BaseNodePath + "/" + treeNode.Parent.FullPath;
            }
            else
                sysTreeView.BaseNodePath = treeView.BaseNodePath; //处理从OT结点打开新窗口时的新窗口BaseNodePath


            return sysTreeView;
        }

        private static TreeViewOpr getTreeViewOpr()
        {
            if (treeViewOpr == null)
                return new TreeViewOpr();
            return treeViewOpr;
        }

        public static void SetSysXmlExpire()
        {
            treeViewOpr = null;
            xdoc = null;
            //Util.ActiveTreeView = null;
            //LivelySysTreeViewList = new ArrayList();
            
        }

        private static XmlDocument getXmlDocument()
        {
            if (xdoc == null || xdoc.DocumentElement ==null)
            {
                 XMLPath();

                //MessageBox.Show(xmlpath);
                using (XmlTextReader xreader = new XmlTextReader(otXML))
                {
                    xdoc = new XmlDocument();
                    Util.SysXmlDocument = xdoc;      


                    xdoc.Load(xreader);

                    //back up every start
                    xdoc.Save(otXML + ".bak");

                    // xreader.Close();
                }
                return xdoc;
            }
            return xdoc;
        }

        /*public static void saveNodes() {
            XmlTextWriter xwriter = new XmlTextWriter(XMLPath(), null);
            xdoc.Save(xwriter);
        }*/
        //获得单态模式下的TypeMaxNum.xml文件的DOM
        public static XmlDocument getTypeMaxNumXML()
        {
            if (typeMaxNum == null)
            {
                using (XmlTextReader reader = new XmlTextReader(typeMaxNumXML))
                {
                    typeMaxNum = new XmlDocument();
                    ResourceManager resourceManager = new ResourceManager("RuleCode.ObjectTree.Properties.Resources", new DeleteContextMenu().GetType().Assembly);
                    string content = resourceManager.GetObject("NodesTemplates").ToString();     
                   
                  
                  
                  
                    typeMaxNum.Load(resourceManager.GetStream("NodesTemplates"));
                }

                return typeMaxNum;
            }
            return typeMaxNum;
        }

        //获得单态模式下的NodesTemplate.xml文件的DOM
        public static XmlDocument getNodesTemplateXML()
        {
            if (nodesTemplate == null)
            {
                using (XmlTextReader reader = new XmlTextReader(nodesTemplateXML))
                {
                    nodesTemplate = new XmlDocument();
                   // nodesTemplate.Load(reader);

                    ResourceManager resourceManager = new ResourceManager("RuleCode.ObjectTree.Properties.Resources", 
                        new DeleteContextMenu().GetType().Assembly);
                    //string content = resourceManager.GetObject("NodesTemplates").ToString();
                    nodesTemplate.LoadXml(resourceManager.GetObject("NodesTemplates").ToString());
                    //nodesTemplate.LoadXml
                   
                }
                return nodesTemplate;
            }
            return nodesTemplate;
        }

        //获得结点的父视图
        public SysTreeView getNodeSubView(SysTreeNode node)
        {
            return (SysTreeView)node.TreeView;
        }

        //填充结点，若有子子结果，将子结点显示为可扩展
        public void fillNodes(XmlNode node, TreeNodeCollection nodesCollection)
        {
            //先加节点
            SysTreeNode newTreeNode = fillNode(node, nodesCollection);
            //newTreeNode.
            //扩展结点
            newTreeNode.Expand();
            //加节点的子结点
            /*
            if (node.HasChildNodes)
            {
                XmlNodeList nodeList = node.ChildNodes;
                foreach (XmlNode xmlNode in nodeList)
                {
                    //fillNodes(xmlNode, newTreeNode.Nodes);
                    SysTreeNode subNode = fillNode(xmlNode, newTreeNode.Nodes);
                    
                    subNode.FillSubNodes(subNode);
                }
            }
            */
        }

        public static SysTreeNode fillNode(XmlNode node, TreeNodeCollection nodesCollection)
        {
            SysTreeNode newTreeNode = new SysTreeNode();
            //ContextMenu contextMenu = new ContextMenu();

            newTreeNode.Text = node.Name;

            //newTreeNode.ImageIndex = int.Parse(node.Attributes.GetNamedItem("ID").Value);
            //newTreeNode.SelectedImageIndex = int.Parse(node.Attributes.GetNamedItem("ID").Value);
            newTreeNode.ImageKey = node.Attributes.GetNamedItem("Type").Value + ".ico";
            newTreeNode.SelectedImageKey = node.Attributes.GetNamedItem("Type").Value + ".ico";
            newTreeNode.Name = node.Name;
            //newTreeNode.Tag = node;
            newTreeNode.SysXmlNode = node;
            //node.
            nodesCollection.Add(newTreeNode);
            //TODO:如果XML有子结点，先填入一个假结点用来显示+号
            if (node.HasChildNodes)
            {
                SysTreeNode treeNode = new SysTreeNode("JustForFun");
                newTreeNode.Nodes.Add(treeNode);
            }

            return newTreeNode;
        }

        //从AOTXML搬过来的代码

        public static string XMLPath()
        {
            //string aotFolder = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + Util.DevArea;
            if (string.IsNullOrEmpty(Util.DevArea ))
            {
                Util.DevArea = "DAT";
            }
            string aotFolder =Util.GetObjDataPath .TrimEnd (GlobalStaticDirectoryPath .ObjectData .ToCharArray ()) ;//Util.OTPath;
            DirectoryInfo dinfo = new DirectoryInfo(aotFolder);
            if (!dinfo.Exists)
            {
                dinfo.Create();
            }
            string aotFile = Path.Combine(aotFolder, "aotFile.xml");
            if (!File.Exists(aotFile))
            {
                createAOTXMLFile(aotFile);
            }
            otXML = Path.Combine(aotFolder, "aotFile.xml");           
            
            nodesTemplateXML = Path.Combine(aotFolder, "NodesTemplates.xml");
            if (!File.Exists(nodesTemplateXML))
            {
                createNodeTemplateXMLFile(nodesTemplateXML);
            }
            //typeMaxNumXML = Path.Combine(aotFolder, "TypeMaxNum.xml");
            //if (!File.Exists(typeMaxNumXML))
            //{
            //    createTypeMaxNumXMLFile(typeMaxNumXML);
            //}
            return aotFile;
        }
        internal static void createNodeTemplateXMLFile(string _templateFile)
        {
        //    XmlDocument xmldoc = new XmlDocument();


        //    XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "AOT", "");
        //    xmldoc.AppendChild(xmlnode);
        //    XmlElement x_aot = xmldoc.CreateElement("", "NodesTemplates", "");
        //    x_aot.SetAttribute("ID", "1");
        //    x_aot.SetAttribute("Type", "AOT");
        //    xmldoc.AppendChild(x_aot);
            //ResourceManager resourceManager = new ResourceManager("RuleCode.ObjectTree.Properties.Resources", new DeleteContextMenu().GetType().Assembly);
            //string content = resourceManager.GetObject("NodesTemplates").ToString();
            //System.IO.File.WriteAllText(_templateFile, content);
        
            

        }
        internal static void createTypeMaxNumXMLFile(string _typeFile)
        {
            XmlDocument xmldoc = new XmlDocument();


            XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "AOT", "");
            xmldoc.AppendChild(xmlnode);
            XmlElement x_aot = xmldoc.CreateElement("", "TypeMaxNum", "");           
            xmldoc.AppendChild(x_aot);
            XmlElement sub = xmldoc.CreateElement("", "ExtendDataType", "");
            sub.SetAttribute("ID", "1000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Table");
            sub.SetAttribute("ID", "2000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("TableField");
            sub.SetAttribute("ID", "3000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("MenuItem");
            sub.SetAttribute("ID", "4000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Menu");
            sub.SetAttribute("ID", "5000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("MenuItemInMenu");
            sub.SetAttribute("ID", "6000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("EDTRelation");
            sub.SetAttribute("ID", "7000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("BaseEnum");
            sub.SetAttribute("ID", "8000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("EnumElement");
            sub.SetAttribute("ID", "9000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("FieldGroup");
            sub.SetAttribute("ID", "10000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("GroupField");
            sub.SetAttribute("ID", "11000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Index");
            sub.SetAttribute("ID", "12000000");
            x_aot.AppendChild(sub);

            sub = xmldoc.CreateElement("IndexField");
            sub.SetAttribute("ID", "13000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("TableRelation");
            sub.SetAttribute("ID", "14000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("TableRelationField");
            sub.SetAttribute("ID", "15000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("TableMethod");
            sub.SetAttribute("ID", "16000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("TableDeleteAction");
            sub.SetAttribute("ID", "17000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Form");
            sub.SetAttribute("ID", "18000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("FormDesign");
            sub.SetAttribute("ID", "19000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Query");
            sub.SetAttribute("ID", "20000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("QueryMethod");
            sub.SetAttribute("ID", "21000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("QueryDataSource");
            sub.SetAttribute("ID", "22000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("QueryDataSourceSorting");
            sub.SetAttribute("ID", "23000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("QueryDataSourceRange");
            sub.SetAttribute("ID", "24000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("QueryDataSourceField");
            sub.SetAttribute("ID", "25000000");
            x_aot.AppendChild(sub);

            sub = xmldoc.CreateElement("Class");
            sub.SetAttribute("ID", "26000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("MenuItemButton");
            sub.SetAttribute("ID", "27000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Button");
            sub.SetAttribute("ID", "28000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Tab");
            sub.SetAttribute("ID", "29000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("TabPage");
            sub.SetAttribute("ID", "30000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Grid");
            sub.SetAttribute("ID", "31000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Group");
            sub.SetAttribute("ID", "32000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Tree");
            sub.SetAttribute("ID", "33000000");
            x_aot.AppendChild(sub);

            sub = xmldoc.CreateElement("Spilt");
            sub.SetAttribute("ID", "34000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Filter");
            sub.SetAttribute("ID", "35000000");
            x_aot.AppendChild(sub);
            sub = xmldoc.CreateElement("Panel");
            sub.SetAttribute("ID", "36000000");
            x_aot.AppendChild(sub);
            xmldoc.Save(_typeFile);
            
           
        }
        internal static void createAOTXMLFile(string _aotFile)
        {
            XmlDocument xmldoc = new XmlDocument();


            XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "AOT", "");
            xmldoc.AppendChild(xmlnode);

            /*XmlElement x_root = xmldoc.CreateElement("", "ROOT", "");
            x_root.SetAttribute("ID", "0");
            x_root.SetAttribute("Type", "Root");
            xmldoc.AppendChild(x_root);
            */

            XmlElement x_aot = xmldoc.CreateElement("", "对象设计器", "");
            x_aot.SetAttribute("ID", "1");
            x_aot.SetAttribute("Type", "AOT");
            xmldoc.AppendChild(x_aot);

            XmlElement x_datadictionary = xmldoc.CreateElement("", "数据字典", "");
            x_datadictionary.SetAttribute("ID", "2");
            x_datadictionary.SetAttribute("Type", "DataDictionary");
            //XmlElement x_marco = xmldoc.CreateElement("", "宏", "");
            //x_marco.SetAttribute("ID", "3");
            //x_marco.SetAttribute("Type", "Marcoes");
            //XmlElement x_class = xmldoc.CreateElement("", "类", "");
            //x_class.SetAttribute("ID", "4");
            //x_class.SetAttribute("Type", "Classes");
            //XmlElement x_form = xmldoc.CreateElement("", "窗体", "");
            //x_form.SetAttribute("ID", "5");
            //x_form.SetAttribute("Type", "Forms");
            //XmlElement x_report = xmldoc.CreateElement("", "报表", "");
            //x_report.SetAttribute("ID", "6");
            //x_report.SetAttribute("Type", "Reports");
            //XmlElement x_query = xmldoc.CreateElement("", "查询", "");
            //x_query.SetAttribute("ID", "7");
            //x_query.SetAttribute("Type", "Queries");
            //XmlElement x_job = xmldoc.CreateElement("", "工作", "");
            //x_job.SetAttribute("ID", "8");
            //x_job.SetAttribute("Type", "Job");
            XmlElement x_menu = xmldoc.CreateElement("", "菜单", "");
            x_menu.SetAttribute("ID", "9");
            x_menu.SetAttribute("Type", "Menus");
            XmlElement x_menuitems = xmldoc.CreateElement("", "目录项", "");
            x_menuitems.SetAttribute("ID", "10");
            x_menuitems.SetAttribute("Type", "MenuItems");
            //var menuItemGroupView = xmldoc.CreateElement("", "显示", "");
            //menuItemGroupView.SetAttribute("ID", "10");
            //menuItemGroupView.SetAttribute("Type", OT.MenuItemGroup);
            //var menuItemGroupAction = xmldoc.CreateElement("", "动作", "");
            //menuItemGroupAction.SetAttribute("ID", "10");
            //menuItemGroupAction.SetAttribute("Type", OT.MenuItemGroup);
            //var menuItemGroupOutput = xmldoc.CreateElement("", "输入", "");
            //menuItemGroupOutput.SetAttribute("ID", "10");
            //menuItemGroupOutput.SetAttribute("Type", OT.MenuItemGroup);
            XmlElement x_webForms = xmldoc.CreateElement("", "WebForms", "");
            x_webForms.SetAttribute("ID", "20");
            x_webForms.SetAttribute("Type", OT.WebForms);
          
            
            //XmlElement x_web = xmldoc.CreateElement("", "网络", "");
            //x_web.SetAttribute("ID", "11");
            //x_web.SetAttribute("Type", "Webs");
            //XmlElement x_resource = xmldoc.CreateElement("", "资源", "");
            //x_resource.SetAttribute("ID", "12");
            //x_resource.SetAttribute("Type", "Resources");
            //XmlElement x_reference = xmldoc.CreateElement("", "引用", "");
            //x_reference.SetAttribute("ID", "13");
            //x_reference.SetAttribute("Type", "References");
            x_aot.AppendChild(x_datadictionary);
            //x_aot.AppendChild(x_marco);
            //x_aot.AppendChild(x_class);
            //x_aot.AppendChild(x_form);
            x_aot.AppendChild(x_webForms);
            //x_aot.AppendChild(x_report);
            //x_aot.AppendChild(x_query);
            //x_aot.AppendChild(x_job);
            x_aot.AppendChild(x_menu);
            x_aot.AppendChild(x_menuitems);
            //x_aot.AppendChild(x_web);
            //x_aot.AppendChild(x_resource);
            //x_aot.AppendChild(x_reference);
           


            XmlElement x_table = xmldoc.CreateElement("", "表", "");
            x_table.SetAttribute("ID", "14");
            x_table.SetAttribute("Type", "Tables");
            XmlElement x_ext = xmldoc.CreateElement("", "字段类型", "");
            x_ext.SetAttribute("ID", "15");
            x_ext.SetAttribute("Type", "ExtendDataTypes");
            //XmlElement x_view = xmldoc.CreateElement("", "视图", "");
            //x_view.SetAttribute("ID", "16");
            //x_view.SetAttribute("Type", "Views");
            XmlElement x_enum = xmldoc.CreateElement("", "枚举", "");
            x_enum.SetAttribute("ID", "17");
            x_enum.SetAttribute("Type", OT.BaseEnums);
            x_datadictionary.AppendChild(x_table);
            x_datadictionary.AppendChild(x_ext);
            //x_datadictionary.AppendChild(x_view);
            x_datadictionary.AppendChild(x_enum);

            //xmltext = xmldoc.CreateTextNode("Tom");
            //x_ext.AppendChild(xmltext);
            XmlElement menuItemGroup_View = xmldoc.CreateElement("", "显示", "");
            menuItemGroup_View.SetAttribute("ID", "10");
            menuItemGroup_View.SetAttribute("Type", OT.MenuItemGroup);
            XmlElement menuItemGroup_Output = xmldoc.CreateElement("", "输入", "");
            menuItemGroup_Output.SetAttribute("ID", "10");
            menuItemGroup_Output.SetAttribute("Type", OT.MenuItemGroup);
            XmlElement menuItemGroup_Action = xmldoc.CreateElement("", "动作", "");
            menuItemGroup_Action.SetAttribute("ID", "10");
            menuItemGroup_Action.SetAttribute("Type", OT.MenuItemGroup);
            x_menuitems.AppendChild(menuItemGroup_View);
            x_menuitems.AppendChild(menuItemGroup_Output);
            x_menuitems.AppendChild(menuItemGroup_Action);


            XmlElement x_singleWebForms = xmldoc.CreateElement("", OT.WebFormSingle, "");
            x_singleWebForms.SetAttribute("ID", "100");
            x_singleWebForms.SetAttribute("Type", OT.WebFormSingles);
            XmlElement x_masterSlaveWebForms = xmldoc.CreateElement("", OT.WebFormMasterSlave, "");
            x_masterSlaveWebForms.SetAttribute("ID", "100");
            x_masterSlaveWebForms.SetAttribute("Type", OT.WebFormMasterSlaves);
            XmlElement x_treeWebForms = xmldoc.CreateElement("",OT.WebFormTree, "");
            x_treeWebForms.SetAttribute("ID", "100");
            x_treeWebForms.SetAttribute("Type", OT.WebFormTrees);
            XmlElement x_parameterWebForms = xmldoc.CreateElement("", OT.WebFormParameter, "");
            x_parameterWebForms.SetAttribute("ID", "100");
            x_parameterWebForms.SetAttribute("Type", OT.WebFormParameters);
            XmlElement x_paraByUserWebForms = xmldoc.CreateElement("", OT.WebFormParaByUser, "");
            x_paraByUserWebForms.SetAttribute("ID", "100");
            x_paraByUserWebForms.SetAttribute("Type", OT.WebFormParaByUsers);
            XmlElement x_relationWebForms = xmldoc.CreateElement("", OT.WebFormRelation, "");
            x_relationWebForms.SetAttribute("ID", "100");
            x_relationWebForms.SetAttribute("Type", OT.WebFormRelations);
            XmlElement x_blankWebForms = xmldoc.CreateElement("", OT.WebFormBlank, "");
            x_blankWebForms.SetAttribute("ID", "100");
            x_blankWebForms.SetAttribute("Type", OT.WebFormBlanks);
            x_webForms.AppendChild(x_singleWebForms);
            x_webForms.AppendChild(x_masterSlaveWebForms);
            x_webForms.AppendChild(x_treeWebForms);
            x_webForms.AppendChild(x_parameterWebForms);
            x_webForms.AppendChild(x_paraByUserWebForms);
            x_webForms.AppendChild(x_relationWebForms);
            x_webForms.AppendChild(x_blankWebForms);

            xmldoc.Save(_aotFile);
        }

        public static void saveToXML()
        {
            //将DOM保存到XML文件中

            xdoc.Save(XMLPath());
           // typeMaxNum.Save(typeMaxNumXML);
          //  nodesTemplate.Save(nodesTemplateXML);
        }

        public static void saveOTXML()
        {
            xdoc.Save(XMLPath());
        }


        //开发环境选择
        /*private string devArea;
        [DefaultValue("DAT")]
        public string DevArea
        {
            get { return devArea; }
            set { devArea = value; }
        }*/
    }

    //改写共同方法

    public class SysTreeNode : TreeNode
    {
        private BaseProperty property;

        public BaseProperty Property
        {
            get { return property; }
            set { property = value; }
        }

        private XmlNode xmlNode;

        public XmlNode SysXmlNode
        {
            get { return xmlNode; }
            set { xmlNode = value; }
        }

        public SysTreeNode()
        {
        }

        public SysTreeNode(string text)
            : base(text)
        {
            Name = text;
            
        }

        public void FillSubNodes(SysTreeNode treeNode)
        {
            //XmlNode xmlNode = (XmlNode)treeNode.Tag;
            XmlNode xmlnode = treeNode.xmlNode;
            if (xmlnode.HasChildNodes)
            {
                XmlNodeList nodeList = xmlNode.ChildNodes;
                foreach (XmlNode node in nodeList)
                {
                    TreeViewOpr.fillNode(node, treeNode.Nodes);
                }
            }
        }

        public SysTreeNode FindNode(string name)
        {
            Expand();
            foreach (TreeNode treeNode in Nodes)
            {
                if (treeNode.Text.Equals(name))
                {
                    return (SysTreeNode)treeNode;
                }
            }
            return null;
        }

        /// <summary>
        /// Expand()不调用OnBeforeExpand()方法，新ExpandNode()将OnBeforeExpand()中的逻辑搬了过来。
        /// </summary>
        public void ExpandNode()
        {
            if (Nodes.Count == 1 && Nodes[0].Text.Equals("JustForFun"))
            {
                Nodes.Clear();
                FillSubNodes(this);
            }
        }

        public void ExpandAllNodes()
        {
            ExpandNode();
            foreach (SysTreeNode node in Nodes)
            {
                // node.ExpandNode();
                node.ExpandAllNodes();
            }
        }

        public override object Clone()
        {
            SysTreeNode node = (SysTreeNode)base.Clone();
            node.SysXmlNode = SysXmlNode;

            return node;
        }

        public override string ToString()
        {
            return Text;
        }
    }
}